import { Component, OnInit, ViewChild, ViewContainerRef, } from '@angular/core';
import { ServiceQueryService } from "./service-query.service";
import { Router } from "@angular/router";
import { AppPaginationComponent, PaginationModel } from "../../../widgets/pagination/pagination.component";
import { environment } from "../../../../environments/environment";
import * as _ from "lodash";
import { AnnuityFileComponent } from "app/pages/annuity/modal/file/file.component";
import { DataService } from '../../../services/data.service';
import { Util } from 'app/common/util';
import { AreaDataCnModule } from "../../../widgets/area-data-cn/area-data-cn.module";
import { AreaDataCnComponent } from "../../../widgets/area-data-cn/area-data-cn.component";

@Component({
  selector: 'app-service-query',
  templateUrl: './service-query.component.html',
  styleUrls: ['./service-query.component.scss'],
  providers: [ServiceQueryService]
})
export class ServiceQueryComponent implements OnInit {
  // 获取模板内的第一个指定组件
  @ViewChild(AreaDataCnComponent)
  public areaDataCnComponent: AreaDataCnComponent;
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 投管人
  public sInvestSelectList: any;
  // 移交投管人
  public sInvestorSelectList: any;
  // 其他投资管理人
  public investorSelectList: any;
  // 项目经理
  public managerSelectList: any;
  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }
  // 获取字典值
  public dictionaryList: any = {
    // RECORDORG_TYPE: [],  // 备案机构
    TERM_TYPE: [],   // 产品类别
    // LINK_PRINCIPAL_NO: [],   // 受托人
    // TRUSTEE: [],   // 托管人
    INVEST: [], // 投管人
    MANAGER: [],    // 账管人
    AREA: [],   // 所属地区
    CALLING: [], // 所属行业
    CENTRAL_ENTERPRISER: [], // 是否央企
    OTHER_INVESTOR: [],  // 其他投资管理人、移交投管人
    EMISSION_WAY: [],  // 发行方式
    ANNUITY_TYPE: []
  };
  // 项目经理字典值
  public ProjectManagerList;
  //所属地区
  public area: any;
  // 是否模态框查询
  public isQuery: any = false;
  public isCheckedAll: any = false;
  public dataList;
  // 列表分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  }
  // 分页列表post数据
  public getBody = {
    pageIndex: 1,
    pageSize: 10,
    sStatus: "fundInfo",
    sFundType: '4',
    sFullName: '',  //组合名称 
    sFundCode: '' //组合代码 
  }
  public postBody = {
    pageIndex: 1,
    pageSize: 10,
    sStatus: "fundInfo",
    sFundType: 4,
    sFullName: '',  //组合名称 
    sFundCode: '', //组合代码 
    sContractName: '',  //合同名称 
    sProductType: '',
    sIsAssetTransfer: '0',  //是否资产移交
    sInvestor: '', //移交投管人
    //dSign: '', //签约日期
    //dConfirm: '', //确认日期
    sRecordorgType: '', //备案机构
    sPlanNo: '', //产品登记号
    //dEffective: '', //生效日期
    //dBegin: '', //开始运作日期
    sTermType: '', //期限 
    //dEnd: '', //到期日
    sIsRenewal: '', //是否自动续约
    sLinkPrincipalNo: '', //受托人
    sManager: '', //账管人
    sPrincipal: '', //委托人
    sTrustee: '', //托管人
    // sOtherInvestor: '', //其他投资管理人
    sProjectManager: '', //项目经理
    sManagerNo: '', //投资经理
    sBenchmark: '', //业绩比较基准
    sArea: '', //所属地区
    sCalling: '', // 所属行业
    sIsCentralEnterpriser: '', // 是否央企
    // sIsContainRight: '', //是否含权类,
    // sConfirmationNo: '', //确认函号
    // sEmissionObject: '', //发行对象
    // sEmissionWay: '' //发行方式
    sInvest: '' // 投管人
  };

  constructor(
    public serviceQueryService: ServiceQueryService,
    public dataService: DataService
  ) { }

  ngOnInit() {
    let that = this;
    // 权限处理
    this.dataService.initTree.subscribe(data => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        that.menuData = JSON.parse(SessionMenuData);
        that.menuResourceSet = [];
        _.forEach(that.menuData, (item, index) => {
          if (item.sName == '企业年金') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '服务条目查询') {
                that.menuResourceSet = it.resourceSet;
                sessionStorage.setItem('btn-an', that.menuResourceSet);
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData);
    this.menuResourceSet = [];
    _.forEach(that.menuData, (item, index) => {
      if (item.sName == '企业年金') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '服务条目查询') {
            that.menuResourceSet = it.resourceSet;
            sessionStorage.setItem('btn-an', that.menuResourceSet);
          }
        })
      }
    })
    // 获取字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 备案机构、受托人、托管人
    this.getDictionary();
    // 项目经理
    this.LoadProjectManagerList();
    this.list();
    // 多选下拉框
    window['$'](".select2").select2();
  }
  ngAfterViewInit() {
    let that = this;
    // 备案机构
    window['$']('#sRecordorgTypeSelected').select2({ width: '190px', tags: true });
    window['$']('#sRecordorgTypeSelected').on("select2:select", function (e) {
      that.postBody.sRecordorgType = window['$']('#sRecordorgTypeSelected').select2("val");
    })
    // 期限
    window['$']('#sTermTypeSelected').select2({ width: '190px' });
    window['$']('#sTermTypeSelected').on("select2:select", function (e) {
      that.postBody.sTermType = window['$']('#sTermTypeSelected').select2("val");
    })
    // 受托人
    window['$']('#sLinkPrincipalNoSelected').select2({ width: '190px', tags: true });
    window['$']('#sLinkPrincipalNoSelected').on("select2:select", function (e) {
      that.postBody.sLinkPrincipalNo = window['$']('#sLinkPrincipalNoSelected').select2("val");
    })
    // 账管人
    window['$']('#sManagerSelected').select2({ width: '190px' });
    window['$']('#sManagerSelected').on("select2:select", function (e) {
      that.postBody.sManager = window['$']('#sManagerSelected').select2("val");
    })
    // 托管人
    window['$']('#sTrusteeSelected').select2({ width: '190px', tags: true });
    window['$']('#sTrusteeSelected').on("select2:select", function (e) {
      that.postBody.sTrustee = window['$']('#sTrusteeSelected').select2("val");
    })
    // 所属地区
    window['$']('#sAreaSelected').select2({ width: '190px' });
    window['$']('#sAreaSelected').on("select2:select", function (e) {
      that.postBody.sArea = window['$']('#sAreaSelected').select2("val");
    })
    // 组合类型
    window['$']('#sProductTypeSelected').select2({ width: '190px' });
    window['$']('#sProductTypeSelected').on("select2:select", function (e) {
      that.postBody.sProductType = window['$']('#sProductTypeSelected').select2("val");
    })
    // 所属行业
    window['$']('#sCallingSelected').select2({ width: '190px' });
    window['$']('#sCallingSelected').on("select2:select", function (e) {
      that.postBody.sCalling = window['$']('#sCallingSelected').select2("val");
    })
    // 是否央企
    window['$']('#sIsCentralEnterpriserSelected').select2({ width: '190px' });
    window['$']('#sIsCentralEnterpriserSelected').on("select2:select", function (e) {
      that.postBody.sIsCentralEnterpriser = window['$']('#sIsCentralEnterpriserSelected').select2("val");
    })
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      _.forEach(this.dataList, item => {
        item.isChecked = true;
      });
    } else {
      _.forEach(this.dataList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.dataList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 判断页面查询还是搜索框查询
  loadcheck(type: any) {
    if (type == 'query') {
      this.isQuery = true;
      this.list(1);
    }
    if (type == 'page') {
      this.isQuery = false;
      this.list(1);
    }
  }
  list(pageNum?, pageSize?) {
    let that = this;
    let body: any;
    this.isCheckedAll = false;
    // 判断是页面查询还是搜索框查询
    if (this.isQuery) {
      // 清空页面查询条件
      this.getBody.sFullName = '';
      this.getBody.sFundCode = '';
      // 转换多选下拉框值
      this.postBody.sInvest = Util.transferValue('.sInvest-select');
      this.postBody.sInvestor = Util.transferValue('.sInvestor-select');
      this.postBody.sProjectManager = Util.transferValue('.manager-select');
      // 去空格
      _.forIn(this.postBody, (value, key) => {
        if (key == 'pageSize' || key == 'pageIndex' || key == 'sFundType') {
          // 这里不做处理，排除number类型
        } else {
          that.postBody[key] = _.trim(that.postBody[key]);
        }
      })
      this.postBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
      this.postBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize
      body = _.cloneDeep(this.postBody);
    } else {
      // 去空格
      this.getBody.sFullName = _.trim(this.getBody.sFullName);
      this.getBody.sFundCode = _.trim(this.getBody.sFundCode);
      this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
      this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize
      body = _.cloneDeep(this.getBody);
    }
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.serviceQueryService.list(body).subscribe(data => {
      that.dataList = data.list;
      that.listPageInfo.currentPageNum = data.pageNum;
      that.listPageInfo.totalPages = data.pages;
      that.listPageInfo.total = data.total;
      that.listPageInfo.startRow = data.startRow;
      that.listPageInfo.endRow = data.endRow;
      window['$']('#annuityServiceQuery').modal('hide');
      // // 给表格列支持列拖动效果
      // setTimeout(() => {
      //   Util.colResizable("#fixed-table");
      // }, 100);

      // 给表格列支持列拖动和固定表头效果
      Util.colResizable("#sqList");

    });
  }
  // 分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 显示搜索模态框
  showQuery() {
    window['$']('#annuityServiceQuery').modal('show');
  }
  // 重置搜索
  resetQuery() {
    this.postBody.sFundCode = ''; //组合代码 
    this.postBody.sFullName = '';  //组合名称 
    this.postBody.sContractName = '';  //合同名称 
    this.postBody.sIsAssetTransfer = '0';  //是否资产移交
    this.postBody.sInvestor = '';
    //this.postBody.dSign = ''; //签约日期
    //this.postBody.dConfirm = ''; //确认日期
    this.postBody.sRecordorgType = ''; //备案机构
    this.postBody.sPlanNo = ''; //产品登记号
    // this.postBody.sConfirmationNo = ''; //确认函号
    // this.postBody.sEmissionObject = ''; //发行对象
    // this.postBody.sEmissionWay = ''; //发行方式
    //this.postBody.dEffective = ''; //生效日期
    //this.postBody.dBegin = ''; //开始运作日期
    this.postBody.sTermType = ''; //期限 
    //this.postBody.dEnd = ''; //到期日
    this.postBody.sIsRenewal = ''; //是否自动续约
    this.postBody.sLinkPrincipalNo = ''; //受托人
    this.postBody.sManager = ''; //账管人
    this.postBody.sPrincipal = ''; //委托人
    this.postBody.sTrustee = ''; //托管人
    // this.postBody.sOtherInvestor = ''; //其他投资管理人
    this.postBody.sProjectManager = ''; //项目经理
    this.postBody.sManagerNo = ''; //投资经理
    this.postBody.sBenchmark = ''; //业绩比较基准
    // this.postBody.sArea = ''; //所属地区
    this.postBody.sCalling = ''; // 所属行业
    this.postBody.sIsCentralEnterpriser = ''; // 是否央企
    // this.postBody.sIsContainRight = ''; //是否含权类
    this.postBody.sInvest = ''; // 投管人
    this.postBody.sArea = ''; //所属地区
    this.areaDataCnComponent.reset(); // 所属地区
    window['$']('#sCallingSelected').select2("val", '--请选择--'); // 所属行业
    window['$']('#sIsCentralEnterpriserSelected').select2("val", '--请选择--'); // 是否央企
    window['$']('#sRecordorgTypeSelected').select2("val", '--请选择--'); // 备案机构
    window['$']('#sTermTypeSelected').select2("val", '--请选择--'); // 期限
    window['$']('#sLinkPrincipalNoSelected').select2("val", '--请选择--'); // 受托人   
    window['$']('#sManagerSelected').select2("val", '--请选择--'); // 账管人
    window['$']('#sTrusteeSelected').select2("val", '--请选择--'); // 托管人
    // window['$']('#sManagerNoSelected').select2("val", '--请选择--'); // 投资经理
    // window['$']('#sAreaSelected').select2("val", '--请选择--'); // 所属地区
    window['$']('#sProductTypeSelected').select2("val", '--请选择--'); // 组合类型
    window['$']('.sInvestor-select').select2("val", '--请选择--'); // 移交投管人
    // window['$']('.investor-select').select2("val", '--请选择--'); // 其他投资管理人
    window['$']('.manager-select').select2("val", '--请选择--'); // 项目经理
    window['$']('.sInvest-select').select2("val", '--请选择--'); // 投管人
  }
  // 是否资产移交控制
  IsAssetTransfer() {
    let that = this;
    if (this.postBody.sIsAssetTransfer == '0') {
      this.postBody.sInvestor = '';
      window['$']('.sInvestor-select').select2("val", '--请选择--'); // 移交投管人
    }
  }
  // 项目经理下拉框值
  LoadProjectManagerList() {
    let that = this;
    this.serviceQueryService.getProjectManagerList().subscribe(data => {
      if (data) {
        that.ProjectManagerList = data;
      }
    });
  }
  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.serviceQueryService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.dataList, [colName], ["asc"]);
    if (JSON.stringify(this.dataList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.dataList, [colName], ["desc"]);
    }
    this.dataList = listDataAsc;
  }
  OnAreaChg(event) {
    if (event[1] == '--请选择--' && event[0] != '--请选择--') {
      this.postBody.sArea = this.postBody.sArea + ',' + event[0]
    } else if (event[0] == '--请选择--') {
      this.postBody.sArea = '';
    } else {
      this.postBody.sArea = this.postBody.sArea + ',' + event[0] + "-" + event[1]
    }
  }
  OnAreaCodeChg(event) {
    this.postBody.sArea = event;
  }
  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    let postBody: any;
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem = checkedItem.join(",");
    // 请求body
    if (this.isQuery) {
      postBody = _.cloneDeep(this.postBody);
      postBody['sStatus'] = 'service';
      postBody['nFundNoList'] = checkedItem;
      delete postBody.pageIndex;
      delete postBody.pageSize;
    } else {
      postBody = {
        "nFundNoList": checkedItem,
        "sFullName": this.getBody.sFullName,
        "sFundCode": this.getBody.sFundCode,
        "sFundType": this.getBody.sFundType,
        "sStatus": 'service'
      }
    }
    // 请求Url
    let postUrl = environment.server + '/pms/v1/pension/basicInfo/export/pensionDeptList?token=' + sessionStorage.getItem('token');
    // 导出
    this.serviceQueryService.exportTarget(postUrl, postBody, '企业年金组合列表-服务条目查询');
  }

}
